<script setup>
import { ref } from 'vue'
import {
  articleAddArticleService,
  articleGetArticleDetailService,
  articleEditArticleService
} from '@/api/article'
import ChannelSelect from './ChannelSelect.vue'
import { Plus } from '@element-plus/icons-vue'
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import { ElMessage } from 'element-plus'
import { baseURL } from '@/utils/request'
import axios from 'axios'

const showDrawer = ref(false)
const formData = ref({
  title: '',
  cate_id: '',
  content: '',
  cover_img: '',
  state: ''
})

// 图片文件预览
const imgUrl = ref('')
const onUploadFile = (file) => {
  imgUrl.value = URL.createObjectURL(file.raw) //实现图片文件预览
  formData.value.cover_img = file.raw //传给后端的图片数据
}
const emit = defineEmits(['success'])

const editorRef = ref(null)

const openDrawer = async (row) => {
  showDrawer.value = true
  //   console.log(row)
  if (row.id) {
    // 编辑文章，需要调用后端接口获取文章详情并回显
    const res = await articleGetArticleDetailService(row.id)
    formData.value = res.data.data
    // 接口注意1: cover_img的值, 需要自己拼接服务器前缀地址, 和接口服务的基地址相同
    imgUrl.value = baseURL + formData.value.cover_img
    // 通过接口从后端获取到的图片数据是url格式，但是更新数据提交给后台的时候后端接口规定要file格式的，所以这里需要转换一下
    const file = await imageUrlToFile(imgUrl.value, formData.value.cover_img)
    formData.value.cover_img = file
  } else {
    // 新增文章，将表单数据重置
    formData.value = {
      title: '',
      cate_id: '',
      content: '',
      cover_img: '',
      state: ''
    }
    imgUrl.value = '' //清空图片预览
    editorRef.value.setHTML('') //清空富文本编辑器内容
  }
}
// 将网络图片地址转换为File对象
async function imageUrlToFile(url, fileName) {
  try {
    // 第一步：使用axios获取网络图片数据
    const response = await axios.get(url, { responseType: 'arraybuffer' })
    const imageData = response.data

    // 第二步：将图片数据转换为Blob对象
    const blob = new Blob([imageData], {
      type: response.headers['content-type']
    })

    // 第三步：创建一个新的File对象
    const file = new File([blob], fileName, { type: blob.type })

    return file
  } catch (error) {
    console.error('将图片转换为File对象时发生错误:', error)
    throw error
  }
}

// 发布文章
const onPublish = async (state) => {
  // 将已发布还是草稿状态，存入 state
  formData.value.state = state
  // 将普通表单数据，存入 formData
  const fd = new FormData()
  for (let key in formData.value) {
    fd.append(key, formData.value[key])
  }
  if (formData.value.id) {
    // 编辑文章，调用后端接口
    await articleEditArticleService(fd)
    ElMessage.success('修改成功')
    // 通知父组件刷新列表
    emit('success', 'edit')
    showDrawer.value = false
  } else {
    // 新增文章，调用后端接口
    await articleAddArticleService(fd)
    ElMessage.success('添加成功')
    // 通知父组件刷新列表
    emit('success', 'add')
    showDrawer.value = false
  }
  console.log(formData.value)
}
defineExpose({
  openDrawer
})
</script>
<template>
  <el-drawer
    v-model="showDrawer"
    :title="formData.cate_id ? '编辑文章' : '发布文章'"
    direction="rtl"
    size="50%"
  >
    <el-form :model="formData">
      <el-form-item label="文章标题">
        <el-input
          v-model="formData.title"
          placeholder="请输入文章标题"
        ></el-input>
      </el-form-item>
      <el-form-item label="文章分类">
        <channel-select
          v-model="formData.cate_id"
          width="100%"
        ></channel-select>
      </el-form-item>
      <el-form-item label="文章封面">
        <el-upload
          class="avatar-uploader"
          :auto-upload="false"
          :show-file-list="false"
          :on-change="onUploadFile"
        >
          <img v-if="imgUrl" :src="imgUrl" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="文章内容">
        <div class="editor">
          <quill-editor
            v-model:content="formData.content"
            theme="snow"
            content-type="html"
            ref="editorRef"
          ></quill-editor>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button @click="onPublish('已发布')" type="primary">发布</el-button>
        <el-button @click="onPublish('草稿')">草稿</el-button>
      </el-form-item>
    </el-form>
  </el-drawer>
</template>
<style lang="scss" scoped>
.avatar-uploader {
  :deep() {
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }
    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }
    .el-upload:hover {
      border-color: var(--el-color-primary);
    }
    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      text-align: center;
    }
  }
}
.editor {
  width: 100%;
  :deep(.ql-editor) {
    min-height: 180px;
  }
}
</style>
